<template>
    <div class="edu-page-warp">
        <ul class="switch-ul">
            <li
                v-for="item in tabs"
                :key="item.key"
                @click="handleClick(item.key)"
                :class="{ active: activeTab == item.key }"
            >
                {{ item.label }}
            </li>
        </ul>
        <ConditionCard
            shadow="never"
            body-style="padding: 24px 24px 6px 24px;"
            @search="handleSearch"
            @reset="reset('queryTempletsForm')"
        >
            <el-form
                ref="queryTempletsForm"
                :model="queryTempletsForm"
                label-position="right"
                label-width="90px"
            >
                <el-row :gutter="24" style="height: 50px;">
                    <el-col :span="8">
                        <el-form-item label="年级:" prop="grade">
                            <el-date-picker
                                v-model="queryTempletsForm.grade"
                                value-format="yyyy"
                                type="year"
                                placeholder="选择学年"
                                style="width: 100%"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item
                            v-if="activeTab == 'course'"
                            label="学院:"
                            prop="faculty"
                            style="height:32px;"
                        >
                            <el-select
                                v-model="queryTempletsForm.faculty"
                                filterable
                                clearable
                                style="width: 100%"
                            >
                                <!-- :disabled="role != 4"  -->
                                <el-option
                                    v-for="item in options.faculty"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item
                            v-if="activeTab == 'module'"
                            label="类别:"
                            prop="professionCateGory"
                        >
                            <el-select
                                v-model="queryTempletsForm.professionCateGory"
                                style="width: 100%"
                                clearable
                                collapse-tags
                            >
                                <el-option
                                    v-for="item in options.professionCateGory"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="培养层次:" prop="trainingLevel">
                            <el-select
                                v-model="queryTempletsForm.trainingLevel"
                                style="width: 100%"
                                clearable
                            >
                                <el-option
                                    v-for="item in options.trainingLevel"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item
                            v-if="activeTab == 'course'"
                            label="课程名称:"
                            prop="courseName"
                            :rules="[
                                {
                                    required: true,
                                    message: '课程名称或课程码不能为空'
                                }
                            ]"
                        >
                            <el-select
                                v-model="queryTempletsForm.courseName"
                                filterable
                                remote
                                reserve-keyword
                                placeholder="请输入课程名称或课程码"
                                style="width: 100%"
                                clearable
                                :remote-method="remoteMethod"
                                :loading="loading"
                            >
                                <el-option
                                    v-for="item in options.courseName"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item
                            v-if="activeTab == 'module'"
                            label="模板名称:"
                            prop="modelName"
                        >
                            <el-select
                                v-model="queryTempletsForm.modelName"
                                style="width: 100%;"
                                clearable
                            >
                                <el-option
                                    v-for="item in options.modelName"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </ConditionCard>
        <el-card
            shadow="never"
            body-style="padding: 24px;"
            class="card-margin"
            style="margin-top:-15px;border-top:none"
        >
            <div class="div-main clearfix">
                <div class="float-right">
                    <el-button 
                    v-if="activeTab == 'course'"
                    @click="batchExport">
                        {{ $t('common.btn.export') }}
                    </el-button>
                    <el-button @click="batchEdit">
                        {{ $t('common.btn.batch') + $t('common.btn.edit') }}
                    </el-button>
                </div>
            </div>
            <el-table
                :data="tableData"
                ref="cultureSchemesTable"
                stripe
                style="width: 100%"
                tooltip-effect="light"
                @selection-change="selectionChange"
            >
                <el-table-column type="selection" fixed="left" key="selection"/>
                <el-table-column type="index" label="序号" fixed="left" key="index">
                    <template slot-scope="scope">
                        {{ scope.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column
                    label="方案名称"
                    prop="name"
                    show-overflow-tooltip
                    :width="activeTab == 'course' ? '120' : ''"
                    fixed="left"
                    key="name"
                />
                <el-table-column label="年级" prop="grade" width="60" key="grade" />
                <el-table-column label="培养层次" prop="trainingLevelI18n" width="80" key="trainingLevelI18n" />
                <el-table-column label="类别" width="80" key="professionCateGory">
                    <template slot-scope="scope">
                        {{ scope.row.professionCateGory == '1' ? '专业大类' : '专业' }}
                    </template>
                </el-table-column>
                <el-table-column label="学院" prop="facultyI18n" show-overflow-tooltip key="facultyI18n"/>
                <el-table-column
                    label="专业代码"
                    prop="campusProfession"
                    show-overflow-tooltip
                    v-if="activeTab == 'course'"
                    key="campusProfession"
                />
                <el-table-column label="专业" show-overflow-tooltip key="campusProfessionName">
                    <template slot-scope="scope">
                        <!-- {{
                            activeTab == 'course'
                                ? scope.row.campusProfessionName
                                : scope.row.majorI18n
                        }} -->
                        {{
                            scope.row.campusProfessionName
                        }}
                    </template>
                </el-table-column>
                <el-table-column
                    label="方向"
                    prop="directionName"
                    show-overflow-tooltip
                    v-if="activeTab == 'course'"
                    key="directionName"
                />
                <el-table-column
                    label="课程代码"
                    prop="courseCode"
                    show-overflow-tooltip
                    v-if="activeTab == 'course'"
                    key="courseCode"
                />
                <el-table-column
                    label="课程名称"
                    prop="coursesName"
                    show-overflow-tooltip
                    v-if="activeTab == 'course'"
                    key="coursesName"
                />
                <el-table-column
                    label="学期"
                    prop="semesters"
                    show-overflow-tooltip
                    v-if="activeTab == 'course'"
                    key="semesters"
                />
                <el-table-column 
                    v-if="activeTab == 'course'"
                    key="weeksType"
                    label="课程区分" 
                    width="90">
                    <template slot-scope="props">
                        <span v-if="props.row.weeksType == 0">教学周</span>
                        <span v-if="props.row.weeksType == 1">实践周</span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="考核方式"
                    prop="examModeStr"
                    show-overflow-tooltip
                    width="80"
                    v-if="activeTab == 'course'"
                    key="examModeStr"
                />
                <el-table-column
                    label="课程分类"
                    prop="label"
                    show-overflow-tooltip
                    v-if="activeTab == 'course'"
                    key="label"
                />
                <el-table-column
                    label="学分"
                    prop="credits"
                    show-overflow-tooltip
                    width="50"
                    v-if="activeTab == 'course'"
                    key="credits"
                />
                <el-table-column
                    label="周学时"
                    show-overflow-tooltip
                    v-if="activeTab == 'course'"
                    key="period"
                >
                    <template slot-scope="scope">
                        {{`${scope.row.period}/${scope.row.weeks}`}}
                    </template>
                </el-table-column>
                <el-table-column label="审核状态" prop="status" width="80" fixed="right" key="status">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.status == 3" type="success" size="mini">
                            通过
                        </el-tag>
                        <el-tag v-if="scope.row.status == 1" type="info" size="mini">草稿</el-tag>
                        <el-tag v-if="scope.row.status == 2" type="warning" size="mini">
                            审核中
                        </el-tag>
                        <el-tag v-if="scope.row.status == 4" type="danger" size="mini">禁用</el-tag>
                        <el-tag v-if="scope.row.status == 5" type="danger" size="mini">
                            变更中
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="60px" fixed="right" key="templateId">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            @click="editRow(scope.row.id, scope.row.trainingLevel, scope.row.name,scope.row.templateId,scope.row)"
                        >
                            {{ $t('common.btn.edit') }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="edu-pagination">
                <div class="float-right">
                    <el-pagination
                        :current-page="queryTempletsForm.pageNum_"
                        :page-sizes="[20, 50, 100, 500, 1000]"
                        :page-size="queryTempletsForm.pageSize_"
                        :total="queryTempletsForm.total"
                        layout="total, sizes, prev, pager, next, jumper"
                        style="float: right;margin:0;"
                        @size-change="handleSizeChange"
                        v-if="activeTab == 'course'"
                        @current-change="handleCurrentChange"
                    />
                    <el-pagination
                        :current-page="queryTempletsForm.pageNum2_"
                        :page-sizes="[20, 50, 100, 500, 1000]"
                        :page-size="queryTempletsForm.pageSize2_"
                        :total="queryTempletsForm.total2"
                        layout="total, sizes, prev, pager, next, jumper"
                        style="float: right;margin:0;"
                        @size-change="handleSizeChange2"
                        v-if="activeTab == 'module'"
                        @current-change="handleCurrentChange2"
                    />
                </div>
            </div>
        </el-card>
        <ChangeCultureScheme
            :is-show="showBatchModifyDialog && activeTab=='course'"
            :course-code="queryTempletsForm.courseName"
            :culture-schemes="cultureSchemes"
            :relIdList="relIdList"
            :projId="queryTempletsForm.projId"
            :training-level="trainingLevel"
            :tabType="activeTab"
            :origin-data="tableData"
            v-on:change-visible="changeVisible"
        />
        <ChangeCultureTemplate
            :is-show="showBatchModifyDialog && activeTab=='module'"
            :culture-schemes="cultureSchemes"
            :projId="queryTempletsForm.projId"
            :training-level="trainingLevel"
            :tabType="activeTab"
            :origin-data="tableData"
            :edit-modle="editModle"
            :template-id="templateId"
            v-on:change-visible="changeVisible"
        />
    </div>
</template>
<script>
import bus from 'common/src/utils/bus'
import * as API from 'common/src/api/culture/cultruescheme'
import UTILS from 'common/src/utils/utils'
import { findFaculty } from 'common/src/api/faculty'
import { queryDic, findTrainingLevelByProjId } from 'common/src/api/dictionary'
import ChangeCultureScheme from './ChangeCultureScheme'
import ChangeCultureTemplate from './ChangeCultureTemplate'
import {
    getPower,
    exportProgram,
    findCultureSchemeList,
    getCultureTemplateList,
    findSchemeByTemID,
    getCourses,
    findSchemeByCondition
} from 'common/src/api/culture/bachelor'
import mixin from 'common/src/mixins/index';
export default {
    mixins: [mixin],
    components: { ChangeCultureScheme ,ChangeCultureTemplate},
    data() {
        return {
            queryTempletsForm: {
                grade: '', // 年级
                trainingLevel: '', // 培养层次
                faculty: '', // 学院
                courseName: '',
                // major: "", // 专业
                degreeType: '', // 学位类型
                // formLearning: "", // 学习形式
                // spcialPlan: "", // 专项计划
                // studentAbroad: "", // 国际学生
                status: '1', // 状态
                name: '', // 名称
                pageNum_: 1,
                pageSize_: 20,
                total: 0,
                pageNum2_: 1,
                pageSize2_: 20,
                total2: 0,
                projId: '1',
                professionCateGory: '',
                modelName: ''
                // trainingCategory: []
            },
            queryCultureSchemesForm: {
                name: '', // 名称
                pageNum_: 1,
                pageSize_: 20,
                total: 0,
                templateId: ''
            },
            options: {
                grade: [],
                trainingLevel: [],
                faculty: [],
                // major: [],
                batchCultrueSchemeMajor: [],
                degreeType: [],
                spcialPlan: [],
                formLearning: [],
                studentAbroad: [],
                status: [
                    {
                        label: '通过',
                        value: 3
                    },
                    {
                        label: '草稿',
                        value: 1
                    },
                    {
                        label: '审核中',
                        value: 2
                    },
                    {
                        label: '禁用',
                        value: 4
                    },
                    {
                        label: '变更中',
                        value: 5
                    }
                ],
                templateName: [],
                degreeType: [], // 学位类型
                degreeCategory: [], // 学位类别
                // trainingCategory: [], // 培养类别,
                professionCateGory: [
                    { value: '1', label: '专业大类' },
                    { value: '2', label: '专业' }
                ],
                templates: [],
                campusProfessions: [],
                trainingCategoryId: [],
                projId: [],
                courseName: '',
                modelName: ''
            },
            tabs: [
                { label: '通过课程批量修改', key: 'course' },
                { label: '通过模板批量修改', key: 'module' }
            ],
            tableData: [],
            showBatchModifyDialog: false,
            cultureSchemes: [], //多选中的方案列表
            templatesList:[],
            editModle:false,
            templateId: '',
            role: '',
            trainingLevel: '',
            activeTab: 'course',
            tabType: '',
            relIdList:[],
            filterData: {
                pageNum_: 1,
                pageSize_: 10000
            } //保存筛选条件
        }
    },

    created() {
        this.init()
        this.getRole()
        bus.$on('updateCurrentManageDeptId', currentManageDeptId => {
            this.queryTempletsForm.projId = currentManageDeptId
        })
    },
    watch: {
        'queryTempletsForm.grade': function(n, o) {
            if (this.activeTab == 'course') {
                return
            }
            this.filterData.year = n
            if(n == ""){
                this.options.modelName = []
            }
            if (
                this.filterData.year ||
                this.filterData.trainingLevel ||
                this.filterData.professionCateGory
            ) {
                this.queryTempletsForm.modelName = ''
                this.getModuleName()
            }
        },
        'queryTempletsForm.trainingLevel': function(n, o) {
            if (this.activeTab == 'course') {
                return
            }
            this.filterData.trainingLevel = n
            if (
                this.filterData.year ||
                this.filterData.trainingLevel ||
                this.filterData.professionCateGory
            ) {
                this.queryTempletsForm.modelName = ''
                this.getModuleName()
            }
        },
        'queryTempletsForm.professionCateGory': function(n, o) {
            if (this.activeTab == 'course') {
                return
            }
            this.filterData.professionCateGory = n
            if (
                this.filterData.year ||
                this.filterData.trainingLevel ||
                this.filterData.professionCateGory
            ) {
                this.queryTempletsForm.modelName = ''
                this.getModuleName()
            }
        }
    },
    methods: {
        handleClick(tab) {
            this.activeTab = tab
            this.options.modelName = []
            this.clear()
            if (tab == 'module') {
                findSchemeByTemID(
                    this.queryTempletsForm.modelName,
                    this.queryTempletsForm.pageSize2_,
                    this.queryTempletsForm.pageNum2_
                ).then(res => {
                    if (res.code == 200) {
                        this.tableData = res.data.list
                        this.queryTempletsForm.total2 = res.data.total_
                    }
                })
            }
        },
        init() {
            this.initOptions()
            this.initProjId()
        },
        initProjId() {
            let currentUser = this.global.currentUser
            this.queryTempletsForm.projId = currentUser.currentManageDptId
        },
        getRole() {
            getPower().then(res => {
                this.role = res.data.power
                if (res.data.departmentCode.indexOf(',') != -1) {
                    let departmentCode = res.data.departmentCode.split(',')
                    this.queryTempletsForm.faculty = departmentCode[0]
                } else {
                    this.queryTempletsForm.faculty = res.data.departmentCode
                }
            })
        },
        initOptions() {
            findFaculty().then(res => {
                let data = { X_YX: res.data }
                UTILS.fillSelect({ faculty: 'X_YX' }, data, this.options)
            })
            const data = {
                lang: this.$store.getters.language || 'cn',
                type: 'allChild',
                keys: [
                    'X_PYCC',
                    'X_XXXS',
                    'X_ZXJH',
                    'X_PYLB',
                    'X_XWLB',
                    'X_XWLX',
                    'X_GLBM',
                    'X_PYCC'
                ]
            }
            queryDic(data)
                .then(res => {
                    if (res.code === 200) {
                        // this.fillSelect(res.data);
                        UTILS.fillSelect(
                            {
                                degreeCategory: 'X_XWLB',
                                spcialPlan: 'X_ZXJH',
                                formLearning: 'X_XXXS',
                                degreeType: 'X_XWLX',
                                trainingCategory: 'X_PYLB',
                                project: 'X_GLBM',
                                trainingLevel: 'X_PYCC'
                            },
                            res.data,
                            this.options
                        )
                    }
                })
                .catch(error => {
                    console.log(error)
                })
        },

        reset(ref) {
            this.$refs[ref].resetFields()
            this.queryTempletsForm.degreeType = ''
            this.handleSearch(false)
            if (this.role == 3) this.getRole()
            if (this.activeTab == 'course') {
                this.tableData = []
                this.options.courseName = []
            }
        },
        clear() {
            (this.queryTempletsForm = {
                grade: '', // 年级
                trainingLevel: '', // 培养层次
                faculty: '', // 学院
                degreeType: '', // 学位类型
                status: '1', // 状态
                courseName: '', // 名称
                pageNum_: 1,
                pageSize_: 20,
                total: 0,
                pageNum2_: 1,
                pageSize2_: 20,
                total2: 0,
                projId: '1',
                professionCateGory: '',
                modelName: ''
            }),
                (this.tableData = [])
        },
        getModuleName() {
            getCultureTemplateList(this.filterData)
                .then(res => {
                    if (res.code == 200) {
                        this.options.modelName = res.data.list.map(item => {
                            return {
                                label:
                                    'en' === this.$store.getters.language ? item.nameEn : item.name,
                                value: item.id
                            }
                        })
                    }
                })
                .catch(error => {
                    this.$message({
                        type: 'error',
                        message: '模板名称搜索失败'
                    })
                })
        },
        remoteMethod(query) {
            if (query !== '') {
                this.loading = true
                setTimeout(() => {
                    this.loading = false
                    let parms = {
                        condition: query,
                        approvalFlag:3,
                        pageSize_: 20,
                        pageNum_: 1
                    }
                    getCourses(parms).then(res => {
                        if (res.code == 200) {
                            this.options.courseName = res.data.list.map(item => {
                                return {
                                    label:
                                        'en' === this.$store.getters.language
                                            ? `${item.nameEn}(${item.code})`
                                            : `${item.name}(${item.code})`,
                                    value: item.code
                                }
                            })
                        }
                    })
                }, 300)
            } else {
                this.options.courseName = []
            }
        },
        handleSearch(status = true) {
            if (this.activeTab == 'course') {
                this.$refs['queryTempletsForm'].validate(valid => {
                    if (valid) {
                        let g = this.queryTempletsForm.grade
                        let f = this.queryTempletsForm.faculty
                        let t = this.queryTempletsForm.trainingLevel
                        let c = this.queryTempletsForm.courseName
                        let s = this.queryTempletsForm.pageSize_
                        let n = this.queryTempletsForm.pageNum_
                        findSchemeByCondition(g, f, t, c, s, n).then(res => {
                            if (res.code == 200) {
                                this.tableData = res.data.list
                                this.queryTempletsForm.total = res.data.total_
                            }
                        })
                    } else {
                        return false
                    }
                })
            } else {
                if (status && !this.queryTempletsForm.modelName) {
                    this.$message({
                        type: 'warning',
                        message: '请先选择模板名称'
                    })
                    return
                }
                findSchemeByTemID(
                    this.queryTempletsForm.modelName,
                    this.queryTempletsForm.pageSize2_,
                    this.queryTempletsForm.pageNum2_
                ).then(res => {
                    if (res.code == 200) {
                        this.tableData = res.data.list
                        this.queryTempletsForm.total2 = res.data.total_
                    }
                })
            }
        },
        selectionChange(list) {
            this.templatesList = []
            this.relIdList = []
            this.cultureSchemes = list.map(ele => {
                return ele.id
            })
            this.relIdList = list.map(ele => {
                return ele.relId
            })
            this.templatesList = list.map(ele => {
                return ele.templateId
            })
        },
        handleSizeChange(val) {
            this.queryTempletsForm.pageSize_ = val
            this.handleSearch()
        },
        handleCurrentChange(val) {
            this.queryTempletsForm.pageNum_ = val
            this.handleSearch()
        },
        handleSizeChange2(val) {
            this.queryTempletsForm.pageSize2_ = val
            findSchemeByTemID(
                this.queryTempletsForm.modelName,
                this.queryTempletsForm.pageSize2_,
                this.queryTempletsForm.pageNum2_
            ).then(res => {
                if (res.code == 200) {
                    this.tableData = res.data.list
                    this.queryTempletsForm.total2 = res.data.total_
                }
            })
        },
        handleCurrentChange2(val) {
            this.queryTempletsForm.pageNum2_ = val
            findSchemeByTemID(
                this.queryTempletsForm.modelName,
                this.queryTempletsForm.pageSize2_,
                this.queryTempletsForm.pageNum2_
            ).then(res => {
                if (res.code == 200) {
                    this.tableData = res.data.list
                    this.queryTempletsForm.total2 = res.data.total_
                }
            })
        },
        editRow(id, trainingLevel, name, templateId,row) {
            this.$refs.cultureSchemesTable.clearSelection()
            this.cultureSchemes = [id]
            this.trainingLevel = trainingLevel
            this.templateId = templateId
            this.relIdList = [row.relId]
            this.showBatchModifyDialog = true
        },
        batchEdit() {
            this.editModle = false
            this.templateId = ""
            if (this.$refs.cultureSchemesTable.selection.length === 0) {
                this.$message({
                    message: '请先选择要编辑的方案!',
                    type: 'warning'
                })
                return
            }
            this.trainingLevel = ''
            if(this.activeTab=='module'){
                this.templateId = this.templatesList[0]
                if(this.templatesList.length > 1){
                    let id = this.templatesList[0]
                    this.templatesList.forEach(d =>{
                        if(d != id){
                            this.editModle = true
                        }
                    })
                }
            }
            console.log(this.templatesList)
            console.log(this.editModle)
            this.showBatchModifyDialog = true
        },
        changeVisible() {
            this.showBatchModifyDialog = false
            this.handleSearch(false);
            this.$refs.cultureSchemesTable.clearSelection()
        },
        batchExport() {
            let obj = this.queryTempletsForm
            let params = {
                grade: obj.grade,
                faculty: obj.faculty,
                trainingLevel: obj.trainingLevel,
                courseCode: obj.courseName,
                relIdList:this.relIdList
            }
            exportProgram(params)
        }
    }
}
</script>
<style scoped>
.div-main {
    margin-bottom: 16px;
}
ul.switch-ul {
    padding: 0;
    margin: 0;
}
ul.switch-ul li {
    color: #606266;
    cursor: pointer;
    display: inline-block;
    padding: 5px 10px;
    font-size: 16px;
    border-right: 1px solid #ccc;
}
ul.switch-ul li:last-child {
    border-right: none;
}
ul.switch-ul li.active {
    color: #66b1ff;
    border-bottom: 2px solid #66b1ff;
}
</style>
